package com.shaoshaohuo.app.ui.shipper;

import android.content.Context;
import android.content.Intent;
import android.graphics.Point;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.ScrollView;
import android.widget.TextView;

import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.shaoshaohuo.app.R;
import com.shaoshaohuo.app.adapter.FaceMarketHeadVpAdapter;
import com.shaoshaohuo.app.adapter.RunlineAdapter1;
import com.shaoshaohuo.app.constant.AppConfig;
import com.shaoshaohuo.app.constant.ExtraName;
import com.shaoshaohuo.app.entity.Addressinfo;
import com.shaoshaohuo.app.entity.BaseEntity;
import com.shaoshaohuo.app.entity.BaseUserInfo;
import com.shaoshaohuo.app.entity.Carinfo;
import com.shaoshaohuo.app.entity.FocusImage;
import com.shaoshaohuo.app.entity.Lineinfo;
import com.shaoshaohuo.app.entity.OrderDetail;
import com.shaoshaohuo.app.entity.OrderDetailEntity;
import com.shaoshaohuo.app.entity.PublishedGoodsItem;
import com.shaoshaohuo.app.entity.PublishedGoodsListEntity;
import com.shaoshaohuo.app.entity.UserInfoEntity;
import com.shaoshaohuo.app.entity.UserInfoEntity.UserInfo;
import com.shaoshaohuo.app.framework.IViewFramework;
import com.shaoshaohuo.app.framework.SharedPreferencesHelper;
import com.shaoshaohuo.app.net.HttpRequest;
import com.shaoshaohuo.app.net.HttpRequest.RequestListener;
import com.shaoshaohuo.app.net.RequestService;
import com.shaoshaohuo.app.ui.BaseActivity;
import com.shaoshaohuo.app.ui.PublishManagerActivity;
import com.shaoshaohuo.app.utils.AreaUtil;
import com.shaoshaohuo.app.utils.DeviceHelper;
import com.shaoshaohuo.app.utils.ImageLoadUtil;
import com.shaoshaohuo.app.utils.Location2Util;
import com.shaoshaohuo.app.utils.StringUtil;
import com.shaoshaohuo.app.utils.ToastUtil;
import com.shaoshaohuo.app.utils.ViewUtil;
import com.shaoshaohuo.app.utils.im.IMFactory;
import com.shaoshaohuo.app.view.CustomScrollView;
import com.shaoshaohuo.app.view.MessageDialog;
import com.shaoshaohuo.app.view.ProgressDialog;
import com.shaoshaohuo.app.view.TopbarView;
import com.shaoshaohuo.app.view.wxstyle.ImagePagerActivity;
import com.shaoshaohuo.app.view.wxstyle.NoScrollGridAdapter;
import com.shaoshaohuo.app.view.wxstyle.NoScrollGridView;

import java.util.ArrayList;
import java.util.List;

/**
 * 车源
 */
public class CarOwnerInfoActivity extends BaseActivity implements OnClickListener {

    private TopbarView mTopbarView;

	private String userid;

	private ImageView mHeadViewImage;
	private TextView mUserNameText;
	private TextView mCarNumberText;
//	private TextView mAgeText;
	private ListView mCarLineListview;
	private TextView mCarTypeText;
	private TextView mCarLongText;
	private TextView mCarWeightText;
//	private ListView mCarAddressListview;

    private NoScrollGridView gridview;
    private ArrayList<String> imageUrls;
    private ArrayList<String> smallImageUrls;
    private ScrollView scrollView;
    private LinearLayout btnAddOrder;
    private AddOrderWindow addOrderWindow;
    private TextView tvDistance;
    private TextView tvRealPosition;
    private ImageView ivIm;
    private ImageView ivTel;
    private UserInfo userInfo;

    private String lng = "";
    private String lat = "";
    private static final int REQUEST_CODE_NEW = 101;
    private static final int REQUEST_CODE_HISTORY = 102;
    public static final String EXTRA_GOODS_ID = "EXTRA_GOODS_ID";

    @Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_car_owner);
        lng = SharedPreferencesHelper.getString(SharedPreferencesHelper.Field.LNG, "");
        lat = SharedPreferencesHelper.getString(SharedPreferencesHelper.Field.LAT, "");
		initData();
		initView();
		setUpView();
		requestData();
	}

	private void initData() {
	    userid = this.getIntent().getStringExtra(ExtraName.caruserid);
    }

    private void requestData() {
	    RequestService.getInstance().getUserInfo(this, userid, UserInfoEntity.class, new RequestListener() {
            
            @Override
            public void onSuccess(int requestCode, BaseEntity resultData) {
                dismissLoadingDialog();
                if(resultData.isOk()){
                    UserInfoEntity entity = (UserInfoEntity) resultData;
                    updateUI(entity);
                }else{
                    showToast(resultData.getMsg());
                }
            }
            
            @Override
            public void onFailed(int requestCode, Exception error, String msg) {
                dismissLoadingDialog();
                showToast(R.string.please_check_network);
            }
        });
    }

    protected void updateUI(UserInfoEntity entity) {

        userInfo = entity.getData();
        BaseUserInfo baseinfo = userInfo.getBaseinfo();
        List<Lineinfo> lineinfo = userInfo.getLineinfo();
        List<Addressinfo> addressinfo = userInfo.getAddressinfo();
        Carinfo carinfo = userInfo.getCarinfo();

        mCarNumberText.setText(carinfo.getCarnum());
        
//        LoadUtils.getInstance().loadImage(mHeadViewImage, baseinfo.getAvatar(), 0, 100);
        ImageLoader.getInstance().displayImage(baseinfo.getAvatar(), mHeadViewImage,ImageLoadUtil.getDisplayImageOptions(R.drawable.icon_default_headimage, 180));
        mUserNameText.setText(baseinfo.getRealname());
//        mAgeText.setText("0".equals(baseinfo.getBirthday())?"":baseinfo.getBirthday());
        
        String authStatus = entity.getData().getVerifystatus();
		 if("3".equals(authStatus)){
			 Drawable drawable= getResources().getDrawable(R.drawable.icon_auth_yes);
			 drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
			 mUserNameText.setCompoundDrawables(null,null,drawable,null);
		 }else{
			 Drawable drawable= getResources().getDrawable(R.drawable.icon_un_auth);
			 drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
			 mUserNameText.setCompoundDrawables(null,null,drawable,null);
		 }
        
        RunlineAdapter1<Lineinfo> adapter = new RunlineAdapter1<>(this, lineinfo, false);
        mCarLineListview.setAdapter(adapter);
        int dis = baseinfo.getDistance() < 0 ? 0 : baseinfo.getDistance();
        String disStr = dis > 1000 ? (dis / 1000) + "公里" : "1公里以内";
        if (StringUtil.isNumericEmpty(baseinfo.getLat()) || StringUtil.isNumericEmpty(baseinfo.getLng())
                || StringUtil.isNumericEmpty(lat) || StringUtil.isNumericEmpty(lng)) {
            disStr = "- -";
        } else {
            disStr = Location2Util.getInstance(this).distance(lat, lng, baseinfo.getLat(), baseinfo.getLng()) + "km";
        }
        tvDistance.setText("距离：" + disStr);

        if (!StringUtil.isEmpty(baseinfo.getLat()) && !StringUtil.isEmpty(baseinfo.getLng())) {

            Location2Util.geoSearch(this, Double.parseDouble(baseinfo.getLat()), Double.parseDouble(baseinfo.getLng()), new GeocodeSearch.OnGeocodeSearchListener() {

                @Override
                public void onRegeocodeSearched(RegeocodeResult regeocodeResult, int i) {
                    tvRealPosition.setText("位置：" + regeocodeResult.getRegeocodeAddress().getFormatAddress());
                }

                @Override
                public void onGeocodeSearched(GeocodeResult geocodeResult, int i) {
                    tvRealPosition.setText("位置：--");
                }
            });
        } else {
            tvRealPosition.setText("位置：--");
        }

        
        mCarTypeText.setText(carinfo.getCarcname());
        if(!TextUtils.isEmpty(carinfo.getCarlong())){
        	mCarLongText.setText((Double.parseDouble(carinfo.getCarlong())/1000)+"米");
        }
        if(!TextUtils.isEmpty(carinfo.getCarweight())){
        	mCarWeightText.setText((Double.parseDouble(carinfo.getCarweight())/1000)+"吨");
        }
        
        List<FocusImage> result = new ArrayList<>();
        if(!TextUtils.isEmpty(carinfo.getCarphoto1())){
            FocusImage focusImage = new FocusImage();
            focusImage.setBigimg(carinfo.getCarphoto1());
            result.add(focusImage);
        }
        if(!TextUtils.isEmpty(carinfo.getCarphoto2())){
            FocusImage focusImage = new FocusImage();
            focusImage.setBigimg(carinfo.getCarphoto2());
            result.add(focusImage);
        }
        if(!TextUtils.isEmpty(carinfo.getCarphoto3())){
            FocusImage focusImage = new FocusImage();
            focusImage.setBigimg(carinfo.getCarphoto3());
            result.add(focusImage);
        }
        setMainImages(result);
    }
    
    protected void setMainImages(List<FocusImage> result) {
//        HeaderVpAdapter adapter = new HeaderVpAdapter(this, result, 1, result.size());
//        mHeaderViewPager.setAdapter(adapter);
//        mIndicator.setViewPager(mHeaderViewPager);
//        mIndicator.notifyDataSetChanged();
        List<String> imageList = new ArrayList<String>();
        for (FocusImage fi : result) {
            if (StringUtil.isEmpty(fi.getBigimg()))
                continue;
            imageList.add(fi.getBigimg());
        }
        setMainImages(imageList.toArray(new String[imageList.size()]));
        scrollView.smoothScrollTo(0, 0);
    }

    @Override
     public void onClick(View v) {
        int viewId = v.getId();
        switch(viewId) {
            case R.id.btn_add_order: {
                showAddOrderWindow();
                break;
            }
            default:
                break;
        }
    }

    private void showAddOrderWindow() {
        int[] location = new int[2];
        btnAddOrder.getLocationOnScreen(location);
        addOrderWindow.setCarUserId(userInfo.getUserid());
        addOrderWindow.showAtLocation(btnAddOrder, Gravity.BOTTOM, location[0], btnAddOrder.getHeight());
        backgroundAlpha(0.3f);
    }


    /**
     * 设置添加屏幕的背景透明度
     * @param bgAlpha
     */
    public void backgroundAlpha(float bgAlpha)
    {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = bgAlpha; //0.0-1.0
        getWindow().setAttributes(lp);
    }

    private class HeaderVpAdapter extends FaceMarketHeadVpAdapter<FocusImage> {

        public HeaderVpAdapter(Context context, List<FocusImage> array, int previewCount, int maxListSize) {
            super(context, array, previewCount, maxListSize);
        }

        @Override
        public Object getView(ViewGroup container, final FocusImage data, int position) {

            View view = View.inflate(mContext, R.layout.view_main1_header_item, null);
            ImageView imageView = (ImageView) view.findViewById(R.id.imageView_main1_header_item);
            switch (position) {
            // case 0:
            // //
            // imageView.setImageResource(R.drawable.face_market_disney_detail_top);
            // LoadUtils.getInstance(mContext).loadImage(imageView,
            // R.drawable.face_market_disney_detail_top);
            // break;
            // case 1:
            // //
            // imageView.setImageResource(R.drawable.face_market_vn_detail_top);
            //
            // LoadUtils.getInstance(mContext).loadImage(imageView,
            // R.drawable.face_market_vn_detail_top);
            //
            // break;
            default:
                // FaceHelper.displayImageView(imageView,
                // FaceHelper.getImageServerUrl(Data),
                // IUtil.getBigPicDisplayImageOptions());
//              LoadUtils.getInstance(mContext).loadImage(imageView, FaceHelper.getImageServerUrl(Data));
                break;
            }

//            LoadUtils.getInstance().loadImage(imageView, Data.getBigimg(), new LoadImageListener() {
//                
//                @Override
//                public void onStart(ImageView arg0, String arg1) {
//                    // TODO Auto-generated method stub
//                    
//                }
//                
//                @Override
//                public void onResult(ImageView imageView, String arg1, boolean isLoadSuccess, Bitmap arg3) {
////                  if(isLoadSuccess){
////                      imageView.setBackgroundDrawable(new BitmapDrawable(arg3));
////                  }
//                }
//                
//                @Override
//                public void onProcessChange(ImageView arg0, String arg1, long arg2, long arg3) {
//                    // TODO Auto-generated method stub
//                    
//                }
//            });
            
            ImageLoader.getInstance().displayImage(data.getBigimg(), imageView,ImageLoadUtil.build);
            
            view.setOnClickListener(new OnClickListener() {
                
                @Override
                public void onClick(View v) {
//                  Toast.makeText(mContext, "header", 0).show();
                    
                }
            });
            
            container.addView(view);
            
//            view.setOnClickListener(new OnClickListener() {
//                
//                @Override
//                public void onClick(View v) {
//                    if(!TextUtils.isEmpty(Data.getUrl())){
//                        Intent intent = new Intent(CarOwnerInfoActivity.this,WebBrowserActivity.class);
//                        intent.putExtra(WebBrowserActivity.TITLE, Data.getTitle());
//                        intent.putExtra(WebBrowserActivity.URL, Data.getUrl());
//                        startActivity(intent);
//                    }
//                }
//            });
            
            return view;
        }
        
    }

    private void initView() {
		mTopbarView = (TopbarView) this.findViewById(R.id.topbar);

		mHeadViewImage = (ImageView) this.findViewById(R.id.imageview_sidemenu_headview);
		mUserNameText = (TextView) this.findViewById(R.id.textview_username);
		mCarNumberText = (TextView) this.findViewById(R.id.textview_car_number);
//		mAgeText = (TextView) this.findViewById(R.id.textview_age);
		mCarLineListview = (ListView) this.findViewById(R.id.listview_line_list);
		mCarTypeText = (TextView) this.findViewById(R.id.textview_car_type);
		mCarLongText = (TextView) this.findViewById(R.id.textview_car_long);
		mCarWeightText = (TextView) this.findViewById(R.id.textview_car_weight);
//		mCarAddressListview = (ListView) this.findViewById(R.id.listview_often_address);
        gridview = (NoScrollGridView) this.findViewById(R.id.gridview);
        scrollView = (CustomScrollView) findViewById(R.id.scrollView);
        btnAddOrder = (LinearLayout) findViewById(R.id.btn_add_order);
        tvDistance = (TextView) findViewById(R.id.tv_distance);
        tvRealPosition = (TextView) findViewById(R.id.tv_real_position);
        ivIm = (ImageView) findViewById(R.id.iv_im);
        ivTel = (ImageView) findViewById(R.id.iv_tel);
        
        addOrderWindow = new AddOrderWindow(this);
	}

	private void setUpView() {
		mTopbarView.setCenterText("车源详情");
		mTopbarView.setLeftView(true, true);
        gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                imageBrower(position, imageUrls);
            }
        });

        btnAddOrder.setOnClickListener(this);
        ivIm.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                IMFactory.openChat(CarOwnerInfoActivity.this, userInfo.getUserid());
            }
        });
        ivTel.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                BaseUserInfo bui = userInfo.getBaseinfo();
                DeviceHelper.callPhone(CarOwnerInfoActivity.this, AppConfig.getPhone(bui.getMobile(), bui.getKey()));
            }
        });
	}


    protected void setMainImages(String[] images) {

        imageUrls = new ArrayList<String>();
        smallImageUrls = new ArrayList<String>();
        if (images != null) {
            for (String im : images) {
                imageUrls.add(im);
                int lastPos = im.lastIndexOf(".");
                if (lastPos > 0) {
                    smallImageUrls.add(im.substring(0, lastPos) + "_small" + im.substring(lastPos, im.length()));
                } else {
                    smallImageUrls.add(im);
                }
            }
        }
        if (imageUrls.isEmpty()) { // 没有图片资源就隐藏GridView
            gridview.setVisibility(View.GONE);
        } else {
            gridview.setAdapter(new NoScrollGridAdapter(this, smallImageUrls));
            gridview.setVisibility(View.VISIBLE);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case REQUEST_CODE_NEW:
                if (resultCode == RESULT_OK) {
                    addOrderWindow.dismiss();
                    addOrderWindow = new AddOrderWindow(this);
                    showAddOrderWindow();
                } else {
                    addOrderWindow.dismiss();
                }
                break;
            case REQUEST_CODE_HISTORY:
                if (resultCode == RESULT_OK) {
                    String goodsId = data.getStringExtra(EXTRA_GOODS_ID);
                    addOrderWindow.update(goodsId);
                } else {
                    addOrderWindow.dismiss();
                }
                break;
        }
    }

    /**
     * 打开图片查看器
     *
     * @param position
     * @param urls2
     */
    protected void imageBrower(int position, ArrayList<String> urls2) {
        Intent intent = new Intent(this, ImagePagerActivity.class);
        // 图片url,为了演示这里使用常量，一般从数据库中或网络中获取
        intent.putExtra(ImagePagerActivity.EXTRA_IMAGE_URLS, urls2);
        intent.putExtra(ImagePagerActivity.EXTRA_IMAGE_INDEX, position);
        startActivity(intent);
    }

    /**
     * 下单页面
     */
    class AddOrderWindow extends PopupWindow implements OnClickListener, IViewFramework, PopupWindow.OnDismissListener {
        private final ProgressDialog thisessDialog;
        private View contentView;
        private Context context;
        private TextView tvGoodsName;
        private TextView tvGoodsWeight;
        private TextView tvGoodsStartDate;
        private TextView tvGoodsStartAddress;
        private TextView tvGoodsEndAddress;
        private LinearLayout layoutGoodsNew;
        private LinearLayout layoutGoodsHistory;
        private LinearLayout layoutCommit;

        private String goodsId;
        private String carUserId;
        private ImageView ivClose;

        public void setCarUserId(String carUserId) {
            this.carUserId = carUserId;
        }

        public AddOrderWindow(Context context) {
            super(context);
            this.context = context;
            LayoutInflater inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            contentView = inflater.inflate(R.layout.window_car_add_order, null);
            setContentView(contentView);
            thisessDialog = new ProgressDialog(context);
            WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
            Display display = windowManager.getDefaultDisplay();
            Point p = new Point();
            display.getSize(p);
            //设置SelectPicPopupWindow弹出窗体的宽
            this.setWidth(p.x - ViewUtil.dip2px(context, 19.2f));
            //设置SelectPicPopupWindow弹出窗体的高
            this.setHeight(LinearLayout.LayoutParams.WRAP_CONTENT);
            // 设置SelectPicPopupWindow弹出窗体可点击
            this.setFocusable(true);
            this.setOutsideTouchable(true);
            // 实例化一个ColorDrawable颜色为半透明
            ColorDrawable dw = new ColorDrawable(0xb0000000);
            // 点back键和其他地方使其消失,设置了这个才能触发OnDismisslistener ，设置其他控件变化等操作
            this.setBackgroundDrawable(dw);
            setAnimationStyle(android.R.style.Animation_Dialog);

            setSoftInputMode(PopupWindow.INPUT_METHOD_NEEDED);
            setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);

            init();
        }

        @Override
        public void onClick(View v) {
            int viewId = v.getId();
            switch (viewId) {
                case R.id.layout_goods_new:
                    Intent publishGoodsInfoIntent = new Intent(context, SendGoodsActivity.class);
                    publishGoodsInfoIntent.putExtra(SendGoodsActivity.EXTRA_FROM_FIND_CAR, SendGoodsActivity.EXTRA_FROM_FIND_CAR);
                    startActivityForResult(publishGoodsInfoIntent, REQUEST_CODE_NEW);
                    break;
                case R.id.layout_goods_history:
                    Intent historyGoodsInfoIntent = new Intent(context, PublishManagerActivity.class);
                    historyGoodsInfoIntent.putExtra(PublishManagerActivity.EXTRA_SELECT_GOODS, PublishManagerActivity.EXTRA_SELECT_GOODS);
                    startActivityForResult(historyGoodsInfoIntent, REQUEST_CODE_HISTORY);
                    break;
                case R.id.layout_commit:
                    commit();
                    break;
                case R.id.iv_close:
                    dismiss();
                default:
                    break;
            }
        }

        private void commit() {
            if (StringUtil.isEmpty(carUserId)) {
                ToastUtil.toast("该车源ID为空，下单失败");
                return;
            }
            if (StringUtil.isEmpty(goodsId)) {
                ToastUtil.toast("请选择货源");
                return;
            }
            startLoadingDialog();

            RequestService.getInstance().shipperChooseCar(context, carUserId, goodsId, BaseEntity.class, new RequestListener() {

                @Override
                public void onSuccess(int requestCode, BaseEntity resultData) {
                    dismissLoadingDialog();
                    if (resultData.isOk()) {
                        showToast("下单成功");
                        addOrderWindow.dismiss();
                    } else {
                        showToast(resultData.getMsg());
                    }
                }

                @Override
                public void onFailed(int requestCode, Exception error, String msg) {
                    dismissLoadingDialog();
                    showToast(msg);
                }
            });
        }

        @Override
        public void init() {
            initView();
            initData();
            initListener();
        }

        @Override
        public void initView() {
            tvGoodsName = (TextView) contentView.findViewById(R.id.tv_goods_name);
            tvGoodsWeight = (TextView) contentView.findViewById(R.id.tv_goods_weight);
            tvGoodsStartDate = (TextView) contentView.findViewById(R.id.tv_goods_start_date);
            tvGoodsStartAddress = (TextView) contentView.findViewById(R.id.tv_goods_start_address);
            tvGoodsEndAddress = (TextView) contentView.findViewById(R.id.tv_goods_end_address);
            layoutGoodsNew = (LinearLayout) contentView.findViewById(R.id.layout_goods_new);
            layoutGoodsHistory = (LinearLayout) contentView.findViewById(R.id.layout_goods_history);
            layoutCommit = (LinearLayout) contentView.findViewById(R.id.layout_commit);
            ivClose = (ImageView) contentView.findViewById(R.id.iv_close);

        }

        @Override
        public void initData() {
            RequestService.getInstance().publishedGoodsList(context, "0", "10", PublishedGoodsListEntity.class, new HttpRequest.RequestListener() {

                @Override
                public void onSuccess(int requestCode, BaseEntity resultData) {
                    dismissLoadingDialog();
                    if (resultData.isOk()) {
                        PublishedGoodsListEntity entity = (PublishedGoodsListEntity) resultData;
                        if (entity.getData() != null && entity.getData().getList() != null && entity.getData().getList().size() > 0) {
                            List<PublishedGoodsItem> list = entity.getData().getList();
                            updateUI(list.get(0));
                        } else {
                            //TODO 显示新建对话框
                            MessageDialog md = new MessageDialog(context);
                            md.setMessage("您还未发布货源信息，现在去发布？");
                            md.setLeftBtText("取消");
                            md.setRightBtText("确定");
                            md.setOnBtClickListener(new MessageDialog.OnBtClickListener() {
                                @Override
                                public void onLeftBtClick() {
                                    addOrderWindow.dismiss();
                                }

                                @Override
                                public void onRightBtClick() {
                                    Intent publishGoodsInfoIntent = new Intent(context, SendGoodsActivity.class);
                                    startActivityForResult(publishGoodsInfoIntent, REQUEST_CODE_NEW);
                                }
                            });
                        }


                    } else {
                        showToast(resultData.getMsg());
                    }
                }

                @Override
                public void onFailed(int requestCode, Exception error, String msg) {
                    dismissLoadingDialog();
                    showToast(msg);
                }
            });
        }

        private void updateUI(PublishedGoodsItem goodsItem) {
            tvGoodsName.setText(goodsItem.getOrdername());
            if ("0.00".equals(goodsItem.getShippweight())) {
                tvGoodsWeight.setText(goodsItem.getShipparea() + "立方米");
            } else {
                tvGoodsWeight.setText(goodsItem.getShippweight() + "千克");
            }
            tvGoodsStartDate.setText(goodsItem.getOrigintime());
            tvGoodsStartAddress.setText(AreaUtil.getAreaFullname(goodsItem.getOrigincityid()) + goodsItem.getOriginaddress());
            tvGoodsEndAddress.setText(AreaUtil.getAreaFullname(goodsItem.getReceivecityid()) + goodsItem.getReceiveaddress());
            goodsId = goodsItem.getId();
        }

        @Override
        public void initListener() {
            setOnDismissListener(this);
            layoutGoodsNew.setOnClickListener(this);
            layoutGoodsHistory.setOnClickListener(this);
            layoutCommit.setOnClickListener(this);
            ivClose.setOnClickListener(this);
        }


        @Override
        public void onDismiss() {
            backgroundAlpha(1f);
        }

        /**
         * 根据货源单号，更新视图
         * @param goodsId
         */
        public void update(String goodsId) {
            RequestService.getInstance().getOrderDetail(context, goodsId, OrderDetailEntity.class, new RequestListener() {

                @Override
                public void onSuccess(int requestCode, BaseEntity resultData) {
                    dismissLoadingDialog();
                    if (resultData.isOk()) {
                        OrderDetailEntity entity = (OrderDetailEntity) resultData;
                        OrderDetail od = entity.getData();
                        PublishedGoodsItem item = new PublishedGoodsItem();
                        item.setId(od.getId());
                        item.setShippweight(od.getShippweight());
                        item.setShipparea(od.getShipparea());
                        item.setOrigintime(od.getOrigintime());
                        item.setOriginaddress(od.getOriginaddress());
                        item.setReceiveaddress(od.getReceiveaddress());
                        item.setOrdername(od.getOrdername());
                        item.setOrigincityid(od.getOrigincityid());
                        item.setReceivecityid(od.getReceivecityid());
                        updateUI(item);
                    } else {
                        showToast(resultData.getMsg());
                    }
                }

                @Override
                public void onFailed(int requestCode, Exception error, String msg) {
                    dismissLoadingDialog();
                    showToast(msg);
                }
            });
        }
    }
}
